<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-button-group>
        <!--            <el-button size="small" type="primary" @click="handleView()" >查看</el-button>-->
        <el-button size="small" type="primary" @click="handleAdd()" v-if="canAction.canCreate>0">新增</el-button>
        <el-button size="small" type="success" @click="handleEdit(-1)">查看</el-button>
        <el-button size="small" type="danger" @click="handleDelete()" v-if="canAction.canUnCheck>0">删除</el-button>
        <el-button size="small" type="success" @click="handleRefresh()">刷新</el-button>
        <el-button size="small" type="success" @click="handleCopy()" v-if="template.allowCooperate===1">复制</el-button>
        <el-button size="small" type="success" @click="handleCheck(8)" v-if="canAction.canCheck>0&&template.allowBestFitColumns===1">审核</el-button>
        <el-button size="small" type="success" @click="handleCheck(0)" v-if="canAction.canCheck>0&&template.allowBestFitColumns===1">反审</el-button>
        <el-button size="small" type="primary" @click="queryFromShow=!queryFromShow">查询</el-button>
        <!-- <el-dropdown v-if="canPrint">
          <el-button type="primary" size="small"> 打印 <el-icon class="el-icon--right">
              <arrow-down/>
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-if="printTemplates.length>0" v-for="item in printTemplates" @click="handlePrint(item)" >{{ item.name }}</el-dropdown-item>
              <el-dropdown-item v-else>无模板</el-dropdown-item>

            </el-dropdown-menu>
          </template>
        </el-dropdown> -->
        <el-dropdown >
          <el-button type="primary" size="small">其他
            <el-icon class="el-icon--right">
              <arrow-down/>
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>

              <el-dropdown-item @click="import_file()">Excel导入</el-dropdown-item>
              <el-dropdown-item @click="DownExcel=true">Excel导出</el-dropdown-item>
              <!--                    <el-dropdown-item @click="viewStatus">审批详情</el-dropdown-item>-->
<!--              <el-dropdown-item @click="progressview">查看进度(测)</el-dropdown-item>-->
<!--              <el-dropdown-item v-if="isequipment" @click="progressview">查看进度(测1)</el-dropdown-item>-->
<!--              <el-dropdown-item v-else @click="progressview2">查看进度(测2)</el-dropdown-item>-->
              <el-dropdown-item @click="viewLogs">传送记录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown class="left-10"  v-for="(items,key) in actRules">
          <el-button type="primary" size="small">
              {{ key }}
            <el-icon class="el-icon--right">
              <arrow-down/>
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item type="text" v-for="(item,index) in items"  :disabled="item.isExtFlow===1&&!canShowRule"   size="mini"   :key="index"  @click="runActRules(item)">{{item.ruleName}}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        </el-button-group>
        <vxe-form size="small" :data="queryForm" v-show="queryFromShow" @submit="dfQuery">
          <vxe-form-item v-for="(item,index) in querydfFields" :title="item.fieldTitle" :field="item.fieldName" :key="index" :item-render="{}">
            <template #default="{ data }">
<!--              <vxe-input v-model="data[item.fieldName]" placeholder="请输入条件值"></vxe-input>-->

              <div v-if="item.fieldAreaName==='between'">
                <Between :type="item.dataTypeID===4?'date':'text'" v-model="data[item.fieldName]"></Between>
              </div>
              <div v-else>
                <vxe-input   v-model="data[item.fieldName]" placeholder="请输入条件值"></vxe-input>
              </div>
            </template>
          </vxe-form-item>

          <vxe-form-item>
            <template #default>
              <vxe-button size="small" v-if="querydfFields.length>0" type="submit" status="primary">查询</vxe-button>
              <vxe-button size="small" v-if="querydfFields.length>0" type="reset">重置</vxe-button>
              <vxe-button size="small" type="primary" v-if="isequipment" @click="handleQuery()">高级查询</vxe-button>

            </template>
          </vxe-form-item>
        </vxe-form>

      </el-header>
      <el-main>
        <el-row>
          <el-col :span="24">

            <vxe-table border resizable size="mini" show-overflow keep-source :data="MainTableData" height="380"
                       ref="Main" :name="MainTable.tableName" :row-config="{isCurrent: true, isHover: true,height: 30}"
                       @current-change="tableClick" :toolbar-config="tableToolbar" :loading="loading"
                       :show-footer="ShowFooter[MainTable.tableName]" :footer-method="footerMethod"
                       @cellDblclick="toview">
              <vxe-column type="checkbox" width="40"></vxe-column>
              <vxe-column field="RecordID" width="60" align="center" title="ID"></vxe-column>
              <vxe-column field="StatusCode" width="70" align="center" title="审核状态" type="html" v-if="verifyStatusCode"
                          :formatter="formatStatus"></vxe-column>
              <vxe-column min-width="200" v-for="item in Fields[MainTable.tableName]" :field="item.fieldName"
                          :visible="item.hidden===0" :key="item.fieldID" :title="item.fieldDispName" :params="item"
                          :formatter="formatDate" :edit-render="{}" sortable>
                <template #edit="{ row }">
                  <vxe-input v-model="row[item.fieldName]" type="text"></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
            <vxe-pager size="mini" perfect :loading="MainPageLoading" :current-page="MainPage.pageNum"
                       :page-size="MainPage.pageSize" :total="MainPage.totalResult"
                       :layouts="!isequipment?['PrevPage', 'JumpNumber', 'NextPage','Total']:['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                       @page-change="MainPageChange">
              <template #left>
                <vxe-button style="float: left !important;"  status="primary" @click="examp" v-if="route.path=='/form/W0020'">物料价格对比
                </vxe-button>
                <vxe-button style="float: left !important;"  status="primary" v-if="isequipment" @click="multiple">批量修改
                </vxe-button>
              </template>
            </vxe-pager>

          </el-col>
          <el-col :span="24">
            <el-tabs type="border-card" v-if="DetailTables.length>0">
              <el-tab-pane :label="item.tableTitle" v-for="(item ,name) in DetailTables">
                <div v-if="isequipment" >
                  <div v-if="item.isTemplate" v-html="transferTml(item.templates,DetailsData[item.tableName])"></div>
                  <vxe-table v-else border keep-source show-overflow :id="item.tableName" size="small" height="380" auto-resize
                             :column-config="{resizable: true}"
                             :data="DetailsData[item.tableName]"
                             :ref="el=>itemRefs[item.tableName]=el"
                             :show-footer="ShowFooter[item.tableName]"
                             :footer-method="footerMethod"
                             :tree-config="item.layoutStyle.length>0?{ transform: true,rowField: item.layoutStyle[0],parentField: item.layoutStyle[1]}:null"
                             :sort-config="{defaultSort:item.Orders}"
                             :row-config="{isCurrent: true, isHover: true,height: 30}">
                    <vxe-column type="checkbox" align="center" width="40"></vxe-column>
                    <vxe-column type="seq" align="center" width="60"></vxe-column>
                    <vxe-column title="行号" field="Seq" align="center" :visible="false" width="60"></vxe-column>
                    <vxe-column v-for="it in Fields[item.tableName]" :field="it.fieldName" show-overflow :key="it.fieldID"
                                :width="it.allowFixedWidth>0?it.allowFixedWidth:(item.layoutStyle[0]===it.fieldName?200:100)"
                                :title="it.fieldDispName"
                                :header-align="'center'"
                                :visible="it.hidden===0" :params="it"
                                sortable
                                :tree-node="item.layoutStyle.length===0?false:item.layoutStyle[0]===it.fieldName"  :formatter="formatDate">
                      <template #default="{ row }" v-if="it.componentType===1">
                        {{ getSelectTitle(combo[it.fieldName],row[it.fieldName]) }}
                      </template>
                    </vxe-column>
                  </vxe-table>
                </div>

                <div v-else>
                  <div v-if="DetailsData[item.tableName].length===0"></div>
                  <div v-else>
                  <vxe-form v-for="(items,index) in DetailsData[item.tableName]"  :ref="el=>itemRefs[item.tableName+'_'+index]=el"
                            :key="index" size="mini" :data="items"  title-width="100"  custom-layout>
                    <div style="border: 1px dashed green;padding: 10px;margin-bottom: 5px">
                      <div class="index">{{ index + 1 }}</div>
                      <vxe-form-item v-for="it in  Fields[item.tableName]" :key="it.fieldID" span="24" :title="it.fieldDispName" v-show="it.hidden===0" :field="it.fieldName" :item-render="{name:'input',props:{readonly:true}}" >
                      </vxe-form-item>
                    </div>
                  </vxe-form>
                </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-col>
          <el-drawer
              v-model="drawer"
              size="80%"
              title="审批流程"
              direction="btt"
          >
            <el-icon v-if="!highDetermine" style="position: absolute; top:10px;left: 50%;" @click="()=>{highDetermine= !highDetermine}"><Upload /></el-icon>
            <el-icon v-if="highDetermine" style="position: absolute; top:10px;left: 50%;" @click="()=>{highDetermine= !highDetermine}"><Download /></el-icon>
            <div v-if="highDetermine" style="height: 70%;">
              <sxPse :data="pseDatas.nodeConfig"></sxPse>
            </div>
            <div>
              <div>
                <el-input
                    v-model="textarea"
                    :rows="3"
                    type="textarea"
                    placeholder="请输入备注"
                />
              </div>
              <el-button>打印</el-button>
              <el-button>加签</el-button>
              <el-button @click="()=>{drawer3=true}">...</el-button>
              <el-drawer v-model="drawer3" title="更多" direction="btt">
                <el-button>转发</el-button>
                <el-button>下载</el-button>
                <el-button>暂存代办</el-button>
              </el-drawer>
              <el-button>返回</el-button>
              <el-button type="success" @click="through">通过</el-button>
            </div>
          </el-drawer>

          <el-drawer
              v-model="viewLogsStatus"
              title="传送记录"
          >
            <div style="padding: 10px;">
              <Postlog :Data="selectRow"></Postlog>
            </div>
          </el-drawer>
        </el-row>

      </el-main>
    </el-container>
    <!--查询窗口-->
    <vxe-modal title="查询" v-model="ShowQuery" :show-zoom="isequipment" ref="Query" resize remember
               width="800" :before-hide-method="beforeHideMethod" destroy-on-close transfer>
      <el-button-group>
        <el-button size="small" type="primary"
                   @click="QueryTable.insertAt({field:null,type:'=',value:null,relation:null}, -1)">添加
        </el-button>
        <el-button size="small" type="primary" @click="QueryTable.remove()">清空</el-button>
      </el-button-group>
      <vxe-table border :height="heights" size="mini" :data="queryTable" ref="QueryTable"
                 :edit-config="{trigger: 'click', mode: 'row'}">
        <vxe-column type="seq" width="40"></vxe-column>
        <vxe-column width="230" field="field" title="字段" :cell-render="{}">
          <template #default="{ row }">
            <vxe-select v-model="row.field" placeholder="查询表字段" clearable transfer @change="changeField(row)"
                        @blur="handleFindChange">
              <vxe-optgroup v-for="(tb ,name) in queryFieldss" :label="tb.tableDispName" :key="name">
                <vxe-option v-show="item.hidden===0" v-for="(item,index) in tb.Children" :key="index"
                            :value="tb.tableName+'.'+item.fieldName"
                            :label="tb.tableDispName+'.'+item.fieldDispName"></vxe-option>
              </vxe-optgroup>
            </vxe-select>
          </template>
        </vxe-column>
        <vxe-column width="100" field="type" title="条件" :cell-render="{}">
          <template #default="{ row }">
            <vxe-select v-model="row.type" placeholder="条件" clearable transfer>
              <vxe-option v-for="(item,index) in Filter" :key="index" :value="item.type"
                          :label="item.title"></vxe-option>
            </vxe-select>
          </template>
        </vxe-column>
        <vxe-column title="值" field="value" :cell-render="{}">
          <template #default="{ row }">
            <vxe-input  v-model="row.value" type="text"                       @blur="handleFindChange"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column title="关联" field="relation" :cell-render="{}">
          <template #default="{ row }">
            <vxe-select v-model="row.relation" transfer multiple clearable placeholder="多选时注意顺序!">
              <vxe-option v-for="(item,index) in Relation" :key="index" :value="item.type"
                          :label="item.title"></vxe-option>
            </vxe-select>
          </template>
        </vxe-column>
        <vxe-column title="操作" width="65">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Delete" @click="QueryTable.remove(row)"></el-button>
          </template>
        </vxe-column>
      </vxe-table>

      <div>{{ queryBuildShow }}</div>
      <div style="float: right;margin-top: 10px;">
        <el-button type="primary" size="small" :icon="Check" @click="handleFindChange">验证</el-button>
        <el-button type="primary" size="small" :icon="Check" @click=" handleFind">确认</el-button>
      </div>
    </vxe-modal>
    <!--批次操作-->
    <vxe-modal title="批次处理" v-model="ShowMultiple" width="640">
      <div style="display: flex">
        <el-button size="small" type="primary" @click="MultipleTable.insertAt({field:null,value:null}, -1)">添加
        </el-button>
        <el-input size="small" placeholder="请输入ID值,可输入多个,用逗号(,)分隔" v-model="Multiple.RecordIDs">
          <template slot="prepend">修改记录ID</template>
        </el-input>
      </div>
      <vxe-table border :height="heights" size="mini" :data="Multiple.Data" ref="MultipleTable"
                 :edit-config="{trigger: 'click', mode: 'row'}">
        <vxe-column type="seq" width="40"></vxe-column>
        <vxe-column width="230" field="field" title="字段" :cell-render="{}">
          <template #default="{ row }">
            <vxe-select v-model="row.field" placeholder="表字段" clearable transfer @change="changeField(row)">
              <vxe-optgroup v-for="(tb ,name) in queryFieldss" :label="tb.tableDispName" :key="name">
                <vxe-option v-show="item.hidden===0" v-for="(item,index) in tb.Children" :key="index"
                            :value="tb.tableName+'.'+item.fieldName"
                            :label="tb.tableDispName+'.'+item.fieldDispName"></vxe-option>
              </vxe-optgroup>
            </vxe-select>
          </template>
        </vxe-column>
        <vxe-column title="值" field="value" :cell-render="{}">
          <template #default="{ row }">
            <vxe-input v-model="row.value" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column title="操作" width="65">
          <template #default="{ row }">
            <el-button type="primary" size="small"  @click="MultipleTable.remove(row)">删</el-button>
          </template>
        </vxe-column>
      </vxe-table> <div style="float: right">
      <el-button type="primary" size="small" @click="handleFindEditChange">确认</el-button>
    </div>
    </vxe-modal>
    <!--导出Excel-->
    <vxe-modal title="导出Excel" v-model="DownExcel" width="440">
      <template #default>
        <el-row type="flex" class="row-bg" justify="center" style="margin-bottom: 10px">
          <el-col :span="12">
            <el-button type="primary" icon="el-icon-download" @click="down_file(0)">
              当前页选中记录({{ Main.getCheckboxRecords().length }}条)
            </el-button>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg" justify="center" style="margin-bottom: 10px">
          <el-col :span="12">
            <el-button type="primary" icon="el-icon-download" @click="down_file(1)">
              当前页所有记录({{ Main.getTableData().fullData.length }}条)
            </el-button>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg" justify="center" style="margin-bottom: 10px">
          <el-col :span="12">
            <el-button type="primary" icon="el-icon-download" @click="down_file(2)">
              所有查询记录({{ MainPage.totalResult }}条)
            </el-button>
          </el-col>
        </el-row>
        <el-row v-if="DownFile.load" type="flex" class="row-bg" justify="center" style="margin-bottom: 10px">
          <el-col :span="20" style="text-align: center;">
            <div><i class="el-icon-loading"></i>生成数据中.....</div>
          </el-col>
        </el-row>
        <el-row v-if="DownFile.fileName.length>0" type="flex" class="row-bg" justify="center" style="margin-bottom: 10px">
          <el-col :span="20" style="text-align: center;">
            <a :href="DownFile.url" rel="noopener" target="_blank"> {{ DownFile.fileName }} 下载</a>
          </el-col>
        </el-row>
      </template>
    </vxe-modal>
    <vxe-modal title="查看报价" v-model="exshow" fullscreen width="100%">
      <div>
        <div v-for="(item,index) in exDats" :ref="el=>exRefs[index]=el" style="height: 300px;width: 50%;float: left;"></div>
      </div>
    </vxe-modal>
    <print ref="Print"></print>
  </div>
</template>
<script>
import {getCurrentInstance, onBeforeMount, reactive, ref, toRefs} from "vue"
import {useRoute, useRouter} from 'vue-router'
import XEUtils from 'xe-utils'
import * as echarts from 'echarts';
import templateEdit from "../components/templateEdit.vue"
import sxForm from "/@/views/linkoo/templates/components/form.vue"
import Between from '/@/views/views/components/between.vue';
import {option} from './ex.js'
import {
    addTemplate,
    delTemplate,
    downTemplate,
    editsForm,
    formCheck,
    formcopy,
    GetApproveStatus,
    getCombo,
    getDataGrid,
    getdingfileid,
    getForm,
    getPostLog,
    getTemplate,
    importTemplate,
    listTemplate, multipleEdit,
    rePost, reSendmsg, updateRule,
    uploaddingfileid
} from "/@/api/linkoo/form"
import {ElMessage, ElMessageBox} from 'element-plus'
import {Check, Delete} from '@element-plus/icons-vue'
import VXETable from 'vxe-table'
import sxPse from "../components/sxpse.vue"
import Postlog from "../components/postlogs.vue"
import {onMounted} from "@vue/runtime-core"
import {getCode, getDingTalksCheck} from "/@/api/login";
import print from "/@/views/linkoo/print/print.vue"
import {getPrintList,extu} from "../../../api/linkoo/print";

export default {
  name:"formList",
  components: {templateEdit, sxPse, Postlog, sxForm,print,Between},
  setup(props, ctx) {
    const {proxy} = getCurrentInstance()
    let router = useRouter()
    let drawer = ref(false)
    let Print = ref()
    const route = useRoute()
    let sxformd = ref(null)
    let loading = ref(false)
    let exDats = ref([])
    let fastSearch = ref('')
    let queryBuildShow = ref('')
    let RecordIDS = ref('')
    let verifyStatusCode = ref(false)
    let Add = ref(false)
    let heights = ref(300)
    let sendDingShow = ref(false)
    let ShowEdit = ref(false)
    let saveDisabled = ref(false)
    let ShowQuery = ref(false)
    let QueryTable = ref(null)
    let Query = ref(null)
    let pseDatas = ref(null)
    let MainPageLoading = ref(false)
    let ShowMultiple = ref(false)
    let Main = ref(false)
    let querySelect = ref({})
    let valueData = ref({})
    let DownExcel = ref(false)
    let exRefs = ref([])
    let state = reactive({
      exshow:false,
      windowHeight: document.documentElement.clientHeight,
      highDetermine:false,
        canPrint:false,
      drawer3:false,
      MainTable: {},
      canShowRule:true,
      formDatase: {},
      FooterFields: [],
      viewLogsStatus: false,
      showPrint: false,
      TableData: {},
      templateCode:'',
      itemRefs: {},
      DetailTables: [],
      MainTableData: [],
      queryFromShow: false,
      isequipment: true,
      template: {},
      havePost: false,
      Multiple: {Data: [], RecordIDs: ''},
      selectRow: {},
      approveStatus: {},
      DetailsData: {},
      list2: {},
      combo: {},
      queryFieldss: {},
      actRules: {},
      ShowFooter: {},
      querydfFields: [],
      printTemplates: [],
      queryFields: [],
      Fields: {},
      canAction: {
        "canArchive": 0,
        "canCheck": 0,
        "canCreate": 1,
        "canDownload": 1,
        "canExport": 1,
        "canLock": 0,
        "canPrint": 0,
        "canReview": 0,
        "canUnCheck": 0,
        "canUnLock": 0,
        "canVoided": 0
      },
      DetailPage: {},
      queryForm: {},
      queryTable: [],
      DownFile: {'url': '', 'fileName': '', load: false},
      selectMainData: null,
      MainPage: {pageNum: 1, pageSize: 10, totalResult: 0},
      AllData: {},
      Linker: {},
      tableToolbar: {perfect: true, refresh: true, zoom: true, custom: true},
      StatusCode: 0,
      Relation: [{type: 'or', title: '或'}, {type: 'and', title: '且'}, {type: '(', title: '('}, {type: ')', title: ')'}],
      Filter: [{type: '=', title: '等于'}, {type: '<>', title: '不等于'}, {type: '<', title: '小于'}, {
        type: '<=',
        title: '小于等于'
      }, {type: '>', title: '大于'}, {type: '>=', title: '大于等于'}, {type: 'like', title: '包含'}, {
        type: 'in',
        title: '在列表中'
      }],
    })
    onMounted(()=>{
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          // window.fullWidth = document.documentElement.clientWidth;
          state.windowHeight = window.fullHeight;  // 高
          // that.windowWidth = window.fullWidth; // 宽
        })()
      };
    })
    onBeforeMount(() => {
      getInfo()
      if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i)) {
        state.isequipment = false;
      } else {
        state.isequipment = true
      }
    })
    const runActRules = async(rule) => {
      const rd = Main.value.getCheckboxRecords()
      if(rd.length===0){
        ElMessage({message: "选择数据后再操作", grouping: true, type: 'error',})
      }
      for (let i = 0; i < rd.length; i++){

          switch (rule.ruleType) {
              case 2:
                  await runUpdateRule(rule,rd[i])
                  break
              case 3:
                  await runPostRule(rule,rd[i])
                  break
              case 4:
                  await reSendmsg(rd[i].RecordID,rule.ruleID)
                  break

          }
      }


    }
    const runPostRule = async (rule,RD) => {

      if (rule.isExtFlow === 1 && rule.sourceType === 1 ) {
        if([1,2,9].includes(RD.statusCode)){
          ElMessage.error('单据状态已变更,不允许再次提交!')
          return
        }
        let files = [], corpId = '', kk = getDingTalksCheck()
        await getdingfileid(rule.ruleID, RD.RecordID).then(async res => {
          files = res.data['fileId'] || [];
          corpId = res.data.corpId;
        })
        if (files.length > 0) {
          if (!kk) {
            ElMessage.error('有附件需要在钉钉客户端环境中上传,请在钉钉客户端中重试!')
            return
          } else {
            ElMessage.info('开始传送钉钉表单')
            let sendFiles = files.length
            for (let i = 0; i < files.length; i++) {
              await getCode({type:'dingtalk',corpId:corpId}, async (code) => {
                //  this.dingCode=code
                if (!code) {
                  ElMessage.error('未取得钉钉用户code')
                  // this.sendingLoading = false
                  return
                }
                await uploaddingfileid(files[i], code).then(res => {
                  ElMessage.success(res.message)
                  sendFiles--
                  if (sendFiles === 0) {
                    ElMessage.success("附件上传完毕!")
                    dopotrule(rule,RD.RecordID)
                  }
                })
              })
            }
          }
        } else {
          dopotrule(rule,RD.RecordID)
        }

      } else {
        dopotrule(rule,RD.RecordID)
      }

    }
      const runUpdateRule = async(rule,RD) => {
          updateRule(rule.ruleID, '', RD.RecordID).then(res => {
              if (res.code === 0) {
                  ElMessage.success('成功执行[' + rule.ruleName + ']')
              }
          })
      }


    const dopotrule = (rule,RecordID) => {
      rePost(RecordID, rule.ruleID).then(res => {
        if (res.code === 0) {
          ElMessage.success('ID为['+RecordID+']成功执行[' + rule.ruleName + ']')
        }
      })
    }
    const getSelectTitle=(items,value)=>{
      const k=XEUtils.find(items,item=>item.value===value)
      return k?k['label']:value
    }
    const handleRefresh = () => {
      fastSearch.value = ''
      queryBuildShow.value = ''
      resetData()
      getList(3)
    }
    const getInfo = () => {
      loading.value = true

      state.templateCode=route.path.replace('/form/', '')
      getTemplate(state.templateCode).then(response => {
        if (response['code'] === undefined) {
          setTimeout(() => {
            getInfo()
          }, 1000)
        }
        pseDatas.value=response.data.template.Process!==''?JSON.parse(response.data.template.Process):{}
        state.MainTable = response.data.tables.filter(item => item.tableType === 0)[0]
       // console.log(state.MainTable);
        state.Linker = response.data.linker
        state.DetailTables = response.data.tables.filter(item => item.tableType === 1)
        state.template = response.data.template
        state.formDatase = XEUtils.toStringJSON(response.data.template.FormCode)
        state.actRules= state.ActRules = BuildRules(XEUtils.orderBy((XEUtils.toArray(response.data['actRules'] || []).filter(item => item.isActive === 1)), 'runSeq'))
        state.canAction = response.data.action || {
          "canArchive": 0,
          "canCheck": 0,
          "canCreate": 1,
          "canDownload": 1,
          "canExport": 1,
          "canLock": 0,
          "canPrint": 0,
          "canReview": 0,
          "canUnCheck": 0,
          "canUnLock": 0,
          "canVoided": 0
        }
          state.canPrint=state.canAction.canPrint===1
        state.combo = response.data.combos
        let TB = {}
        state.queryFields = response.data.fields
        response.data.tables.forEach(row => {
          state.DetailsData[row['tableName']] = []
          row.layoutStyle = row.layoutStyle.length > 0 ? row.layoutStyle.split(',') : [];
          const ff = row['onSheet'].toString().split(',')
          if (row['onSheet'].toString() !=='' && ff.length > 0) {
            state.FooterFields = state.FooterFields.concat(ff)
            state.ShowFooter[row.tableName] = true
          }
          row['isTemplate']=false
          if(row['primaryKeyNotice']!==''){
            row['isTemplate']=true
            row['templates']=XEUtils.toStringJSON(row['primaryKeyNotice'])
          }
          TB[row['tableID']] = row['tableName']
          state.TableData[row['tableName']] = []
          state.queryFieldss[row['tableName']] = row
          state.queryFieldss[row['tableName']]['Children'] = []
          row.Fields.forEach(field => {
            field.expandType=XEUtils.toStringJSON(field.expandType)
            if (field.fieldAreaName !== '') {
              state.querydfFields.push(field)
            }
            state.queryFieldss[TB[field.tableID]]['Children'].push(field)
            // if(field.componentID>0&&field.componentType===1){
            //   getCombo(field.componentID).then(res=>{
            //     let arr=res.data.list.map((item,index)=>{
            //       return{label:item.content,value:item.value}
            //     })
            //     state.combo[field.fieldName]=arr
            //   })
            // }
            if (state.Fields[TB[field.tableID]] === undefined) {
              state.Fields[TB[field.tableID]] = []
              state.DetailPage[TB[field.tableID]] = {currentPage: 1, pageSize: 10, totalResult: 0}
            }
            state.Fields[TB[field.tableID]].push(field)
          })
        })

        if (state.DetailTables.length > 0) {
          state.selectTab = state.DetailTables[0].tableName
          // heights.value=heights.value/2-35
        }
        if (state.template.statusCode > 0 || state.canAction.canCheck > 0) {
          verifyStatusCode.value = true
        }
        loading.value = false
        getList(1)
        getPrintList({tid:state.template.templateID}).then(res=>{
          if(res.data.list&&res.data.list.length>0){
            state.printTemplates=res.data.list
          }

        })
      })
    }
    const dfQuery = () => {
      fastSearch.value = '1=1 '
      const FF=[]
      XEUtils.objectEach(XEUtils.pick(state.queryForm, val => !XEUtils.isEmpty(val)), (item, key) => {
        const field=state.querydfFields.find(item=>item.fieldName===key)
        if (field){
              if(field.fieldAreaName==='like'){
                FF.push(XEUtils.template(" {{field}} like '%{{name}}%' ", {name: item,field:key}))
              }else if(field.fieldAreaName==='between'){
                FF.push(XEUtils.template(" {{field}} between '{{name[0]}}' and '{{name[1]}}' ", {name: item.split(","),field:key}))
              }else{
                FF.push(XEUtils.template(" {{field}} {{query}} '{{name}}' ", {query:field.fieldAreaName,name: item,field:key}))
              }
        }else {
          FF.push( ` ${key} like '%${item}%' `)
        }
      })
      fastSearch.value= FF.length>0?fastSearch.value+' and '+FF.join('and'):fastSearch.value
      state.selectMainData = null
      queryBuildShow.value = '';
      getList(1)
    }
    const getList = (types) => {
      const query = {pageNum: state.MainPage.pageNum, pageSize: state.MainPage.pageSize}
      if (!XEUtils.isEmpty(fastSearch.value)) {
        query['QuickSearch'] = fastSearch.value
      }
      if (queryBuildShow.value !== '') {
        query['Search'] = queryBuildShow.value
      }

      listTemplate(state.templateCode, 0, query).then(response => {
        state.MainTableData = response.data.list
        // console.log(state.MainTableData);
        RecordIDS.value = response.data.RecordIDS
        state.MainPage.totalResult = response.data.total

      })
    }
    const formatStatus = ({cellValue}) => {
      return cellValue === 1 ? '<span class="S S1">审核中</span>' : [2,8].includes(cellValue) ? '<span class="S S2">同意</span>' : cellValue === 3 ? '<span class="S S3">中止</span>' :  cellValue === 7 ? '<span class="S S3">退回</span>' : [4,9].includes(cellValue) ? '<span class="S S4">拒绝</span>' :  '未审核'
    }
    const formatDate = ({cellValue, row, column}) => {
      if(!cellValue||cellValue===''){
        return ''
      }
      let extend = XEUtils.toStringJSON(row['Extend'])
      if (extend[column.field] === null || extend[column.field] === undefined) {
        extend[column.field] = cellValue ? cellValue : ''
      }
      if(column.params.dataTypeID===4){
        return XEUtils.toDateString( XEUtils.toStringDate(cellValue), 'yyyy-MM-dd')
      }
      return column.params.dataTypeID!==6?cellValue:XEUtils.get(extend, column.field)
    }
    const footerMethod = ({columns, data}) => {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 1) {
            return '合计'
          }
          if (state.FooterFields.includes(column.property)) {
            return sumNum(data, column.property)
          }
          return null
        })
      ]
    }
    const sumNum = (list, field) => {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count
    }
    const tableClick = () => {
      state.selectMainData = Main.value.getCurrentRecord()
      // getList(2)
      let $table = Main.value
      valueData.value = $table.getCurrentRecord()
      state.StatusCode = XEUtils.toInteger(state.selectMainData['StatusCode'])
      state.canShowRule=![1,2,8].includes(state.StatusCode)
      if (state.template.dingForms !== '' && state.StatusCode < 1 && state.selectMainData.RecordID > 0) {
        sendDingShow.value = true
      }
      getForm(state.template.templateCode, state.selectMainData.RecordID, {}).then(response => {
        state.AllData=response.data
        XEUtils.objectEach(response.data.ChildTables, (item, key) => {
          state.DetailsData[key] = item ? item : []
        })
      })
    }
    const toview = ({row}) => {
      router.push('/form/edit/' + state.template.templateCode + "/" + row.RecordID)
    }
    // 新增
    const handleAdd = () => {
      if (state.canAction.canCreate > 0) {
        router.push('/form/edit/' + state.templateCode + "/0")
      } else {
        ElMessage({message: "没有权限进行此操作", grouping: true, type: 'error',})
      }

    }
    const viewLogs = () => {
      getPostLog({tid: state.template.templateID, rid: state.selectMainData.RecordID}).then(res => {
        state.selectRow = res.data.list
        state.viewLogsStatus = true


      })
      //  setTimeout(()=>{ Postlog.setup().load()},1000)

    }
    const resetData = () => {
      let Data = {}
      sendDingShow.value = false
      state.DetailTables.forEach(row => {
        Data[row.tableName] = []
        state.TableData[row.tableName] = []
      })
      state.selectMainData = {}
      state.Fields[state.MainTable.tableName].forEach(row => {
        state.selectMainData[row.fieldName] = ''
        if (row.fieldName === 'Extend') {
          state.selectMainData[row.fieldName] = '{}'
        }
      })
      state.selectMainData['RecordID'] = 0
      Data[state.MainTable.tableName] = state.selectMainData
    }
    // 获取动态refs，待测试

    let EditData = ref(null)

    const handleEdit = () => {
      //state.selectMainData = Main.value.getCheckboxRecords()
      if (XEUtils.isEmpty(state.selectMainData)) {
        ElMessage({
          message: '点击选择数据再修改',
          grouping: true,
          type: 'info',
        })
        return
      } else {
        router.push('/form/edit/' + state.templateCode + "/" + state.selectMainData.RecordID)
      }
    }
    const handleDelete = () => {
      let $table = Main.value
      const rows = $table.getCheckboxRecords()

      // if (rows.filter(item => item.StatusCode !== 0).length !== 0) {
      //   ElMessage({
      //     message: '选择数据中审核状态包含有非初始状态.不能执行删除!',
      //     type: 'error',
      //   })
      //   return
      // }
      if (rows.length > 0) {

        ElMessageBox.confirm(
            '是否确认删除选中的这些数据项?',
            '警告',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
        ).then(() => {
          delTemplate(state.templateCode, state.MainTable.tableName, XEUtils.pluck(rows, 'RecordID')).then(response => {
            resetData()
            getList(1)
            ElMessage({
              message: '删除成功',
              grouping: true,
              type: 'success',
            })
          })
        }).catch(() => {
        })
      } else {
        ElMessage({
          type: 'info',
          message: '选择数据后再删除!',
        })
      }
    }
    const handleCheck = (status) => {
      const rows = Main.value.getCheckboxRecords()
      if (rows.filter(item => item.StatusCode === status).length !== 0) {
        ElMessage({
          message: '选择数据中有不同审核状态.不能执行操作!',
          type: 'error',
        })
        return
      }
      if (rows.length === 0) {
        ElMessage({
          type: 'info',
          message: '选择数据再操作!',
        })
        return
      }
      ElMessageBox.confirm(
          '是否确认' + (status > 0 ? "审核" : "反审") + "操作?",
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        formCheck({
          template: route.name,
          table: state.MainTable.tableName,
          ids: XEUtils.pluck(rows, 'RecordID'),
          status: status
        }).then(res => {
          ElMessage({
            message: '操作成功',
            grouping: true,
            type: 'success',
          })
          resetData()
          getList(1)
        })
      }).catch(() => {
      })

    }
    const handleCopy = () => {
      if (XEUtils.isEmpty(state.selectMainData)) {
        ElMessage.warning('点击选择数据再复制')
        return
      } else {
        formcopy(state.selectMainData.RecordID, state.template.templateCode).then(res => {
          handleRefresh()
        })
      }


    }
    const handleQuery = () => {
      if (state.queryTable.length === 0) {
        state.queryTable = [{field: null, type: '=', value: null, relation: null, tp: 1, co: 0}]
      }
      ShowQuery.value = true
    }
    const beforeHideMethod = () => {
      state.queryTable = QueryTable.value.getTableData().fullData
    }
    const handleFindChange = () => {
      const data = XEUtils.orderBy(QueryTable.value.getTableData().fullData, '_X_ID')
      let str = ''
      for (let i = 0; i < data.length; i++) {
        const r = data[i]
        if (XEUtils.isEmpty(r.relation) && data.length - i > 1) {
          ElMessage({
            type: 'info',
            message: '多条件之间缺少关联!',
          })
          return false
        }
        let value = ''
        switch (r.type) {
          case 'in':
            value = "('" + r.value.replaceAll(',', "','") + "')";
            break;
          case 'like':
            value = "'%" + r.value + "%'";
            break;
          default:
            value = "'" + XEUtils.toValueString(r.value) + "'";
            break;
        }
        str += r.field + ' ' + r.type + ' ' + value + ' ' + XEUtils.toValueString(r.relation).replaceAll(',', ' ') + ' '
      }
      queryBuildShow.value = str
    }
    const handleFind = () => {
      handleFindChange()
      getList(1)
      Query.value.close()
    }
    const changeField = (row) => {
      row.value = null
      if (row.field === null) return
      const f = row.field.split(".")
      const field = state.Fields[f[0]].find(item => item.fieldName === f[1])
      row.tp = field.dataTypeID
      row.co = field.componentType + field.componentID
      if (field.componentType === 3) {
        state.querySelect = []
        const t = JSON.parse(field.componentFieldName)
        const data = {
          id: field.componentID,
          filter: field.componentFilterExpr,
          fastSearch: '',
          tid: field.componentType,
          pageNum: 1,
          pageSize: 5000
        }
        getDataGrid(data).then(response => {
          state.querySelect = response.data.list.map(row => {
            row['Title'] = row[t[field.fieldName]['t']]
            row['Value'] = row[t[field.fieldName]['v']]
            return row
          })
          state.list2[row.co] = Object.assign([], state.querySelect)
        })
      }
      if (field.componentType === 1) {
        state.querySelect = []
        const t = JSON.parse(field.componentFieldName)
        getCombo(field.componentID).then(res => {
          state.querySelect = res.data.list.map((item, index) => {
            return {Title: item.content, Value: item.value}
          })
          state.list2[row.co] = Object.assign([], state.querySelect)
        })
      }
    }
    const MainPageChange = ({currentPage, pageSize}) => {
      state.MainPage.pageNum = currentPage
      state.MainPage.pageSize = pageSize
      state.selectMainData = null
      getList(1)
    }
    const multiple = () => {
      let $table = Main.value
      const rows = $table.getCheckboxRecords()
      if (rows.length === 0) {
        ElMessage({
          type: 'info',
          message: '请在表中选择要修改的主数据!',
        })
        return false
      }
      state.Multiple['RecordIDs'] = XEUtils.pluck(rows, 'RecordID').join(',')
      ShowMultiple.value = true
    }
    let MultipleTable = ref(null)
    const handleFindEditChange = () => {
      state.Multiple.Data = XEUtils.orderBy(MultipleTable.value.getTableData().fullData, '_X_ID')
        multipleEdit(route.name, state.Multiple).then(res => {
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
          ShowMultiple.value = false
          handleRefresh()
        } else {
          // this.msgError(res.msg)
          ElMessage({
            type: 'info',
            message: res.message,
          })
        }
      })
    }
    const import_file = () => {
      VXETable.readFile().then((params) => {
        const {files} = params
        console.log(files)
        if (files[0].name.indexOf(' ') > -1) {
          ElMessage({
            type: 'error',
            message: "文件名不能含有空格,请修改文件名!",
          })
          return
        }
        let forms = new FormData()
        forms.append('upload-file', files[0])
        importTemplate(route.name, forms).then(res => {
          if (res.code !== 0) {
            // this.msgError(res.msg)
            ElMessage({
              type: 'success',
              message: res.msg,
            })
          }
          getList(1)
        })
      })
    }
    const down_file = (t) => {
      state.DownFile.load = true
      let RDS = ''
      if (t === 0) {
        const data = Main.value.getCheckboxRecords().map((row) => {
          return row.RecordID
        })
        RDS = data.join(',')
      } else if (t === 1) {
        const data = Main.value.getTableData().fullData.map((row) => {
          return row.RecordID
        })
        RDS = data.join(',')
      } else {
        RDS = 'All'
      }
      if (XEUtils.isEmpty(RDS)) {
        state.DownFile.load = false
        ElMessage({
          type: 'info',
          message: "下载数据不能为空!",
        })
        return false
      }
      downTemplate(route.name, RDS).then(res => {
        state.DownFile.load = false
        state.DownFile['url'] = res.data.url
        state.DownFile['fileName'] = res.data.fileName
      })
    }
    let showStatus = ref(false)
    const viewStatus = () => {
      if (state.selectMainData) {
        GetApproveStatus(state.template.templateID, state.selectMainData.RecordID).then(res => {
          state.approveStatus = res.data.info
          state.approveStatus['表单内容'] = JSON.stringify(state.approveStatus['表单内容'], null, "\t")
          state.approveStatus['原始内容'] = JSON.stringify(state.approveStatus['原始内容'], null, "\t")
          showStatus.value = true
        })
      } else {
        ElMessage({
          type: 'info',
          message: "选中记录后再操作!",
        })
      }
    }
    const progressview = (type = 1) => {
      drawer.value = true
    }
    let drawer2 = ref(false)
    const progressview2 = ()=>{
      drawer2.value = false
    }
    const through = () => {
      console.log(sxformd.value.model);
    }
    const getShowFooter = (tableName) => {
      return state.ShowFooter[tableName]
    }
    const focusEvent2  = (val) => {
        querySelect[val].value.showPanel()
        // this.Querylist=this.list2[keys]
    }
    const keyupEvent2  = () => {

    }
    const handlePrint  = (item) => {
      console.log(state.selectMainData);
      
      if (state.selectMainData) {
      console.log(state.selectMainData.StatusCode);
        if(state.selectMainData.StatusCode!=2&&state.selectMainData.StatusCode!=8){
          ElMessage({ type: 'warning',          message: "请审核完成后打印!",        })
          return
        }
        const data={printData:item,rid:state.AllData.RecordID,DataSource:state.AllData,Combo:state.combo,maintable:state.MainTable,detailtable:state.DetailTables}
        console.log(data);
        Print.value.Load(1,data)
        state.showPrint=true
      }else{
          ElMessage({ type: 'warning',          message: "点击记录后再操作!",        })
        }
      }
    
    const transferTml=(template,data)=>{
      let info = XEUtils.toStringJSON(XEUtils.get(data,template['path']))
      XEUtils.objectEach(info, (item, key) => {
        // 对象迭代器，只能用于遍历对象，性能高于 each
        if(XEUtils.isBoolean(item)){
          item = item ? '是':'否'
        }
        info[key] = item
      })
      return XEUtils.template(template['template'],info)
    }
      const BuildRules = (data) => {
          const Rules = {}, rs = ["取数", '更新', '传送','通知']
          XEUtils.arrayEach(data, row => {
              if (row.ruleType>1 &&  row.runTime.split(',').includes('999')){
                  if (Rules[rs[row.ruleType - 1]] === undefined) {
                      Rules[rs[row.ruleType - 1]] = []
                  }
                  Rules[rs[row.ruleType - 1]].push(row)
              }
          })
          return Rules
      }
      const selectEvent2= (item,row,t)=>{
          row.text = item.Title
          row.value = item.Value
          querySelect[t].value.hidePanel()
      }
      const examp =()=>{
        let exdata = Main.value.getCheckboxRecords()
        if(exdata.length==0){
          ElMessage({ type: 'warning',          message: "未选中数据!",        })
          return
        }
        let ov = []
        exdata.forEach((item)=>{
          ov.push(item.RecordID)
        })
        state.exshow=true
        extu(ov.toString()).then((res)=>{
          let arr = []
          let arr2=[]
          res.data.forEach((item)=>{
            if(item.datetime){
              let obj = JSON.stringify(option)
              arr.push({'option':JSON.parse(obj)})
              arr2.push(item)            
            }
          })
          for(let index=0;index<arr.length;index++){
            arr[index].option.title.text=arr2[index].materialname
            arr[index].option.xAxis.data=arr2[index].datetime
            arr[index].option.series[0].data=arr2[index].price
          }
          exDats.value=arr
          setTimeout(()=>{
            exDats.value.forEach((item,index)=>{
              var myChart = echarts.init(exRefs.value[index]);
              myChart.setOption(exDats.value[index].option);
            })
          },500)
          
          console.log(res);
        })
        console.log(option);
      }
    return {
      loading,Print,exDats,echarts,route,
      handlePrint,
      through,
      examp,
      keyupEvent2,
      getShowFooter,querySelect,selectEvent2,
      fastSearch,
      queryBuildShow,
      RecordIDS,
      verifyStatusCode,
      MultipleTable,
      heights,
      sendDingShow,
      ShowEdit,
      saveDisabled,
      Add,
      ShowQuery,
      QueryTable,
      Query,
      valueData,
      drawer,
      sxformd,
      MainPageLoading,
      ShowMultiple,
      DownExcel,
      showStatus,
      Main,
      EditData,
      pseDatas,
      dfQuery,
      handleCheck,
      focusEvent2,
      drawer2,progressview2,
      ...toRefs(state),
      getInfo,
      getList,
      formatStatus,
      formatDate,
      sumNum,
      viewStatus,
      footerMethod,
      tableClick,
      toview,
      handleAdd,
      resetData,
      handleRefresh,
      handleEdit,
      handleDelete,
      handleCopy,
      handleQuery,
      beforeHideMethod,
      handleFindChange,
      handleFind,
      changeField,
      multiple,
      MainPageChange,
      handleFindEditChange,
      import_file,
      down_file,
      progressview,
      viewLogs,
      getSelectTitle,
      Delete,exRefs,
      Check,runActRules,transferTml
    }
  }
}
</script>

<style >
.vxe-body--column .td{
  vertical-align: middle;
}
.common-layout .el-header {
  padding: 0px;
  height: auto;
}

.common-layout .el-main {
  border-radius: 5px;
  height: 100vh;
  padding: 0;
}

.common-layout .left-10 {
  margin-left: 10px;
}

.S {
  line-height: 30px;
  padding: 10px 25px;
  margin: -20px;
}

.S1 {
  background-color: #409eff;
  color: #fff
}

.S2 {
  background-color: #85ce61;
  color: #fff
}

.S3 {
  background-color: #909399;
  color: #fff
}

.S4 {
  background-color: #f56c6c;
  color: #fff
}
</style>